/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fourbox.server;

import fourbox.DBHelper;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hartono
 */
public class Server {

    public static final int SERVER_LISTENING_PORT = 4441;
    public static final int SERVER_DOWNLOAD_PORT = 4442;
    
    public Server() {
    }


    public static void main(String args[]) throws IOException, ClassNotFoundException {        
        Server server = new Server();
        server.start();             
    }
    
    public void start() throws ClassNotFoundException, IOException{
        // initialize repository
        File centralRep = new File("Repository/");
        if (!centralRep.exists()){
            centralRep.mkdir();
        }
        try {
            ArrayList<String> users = DBHelper.getUsers();
            if (users !=null){
                for(String user : users){
                    File userRep = new File("Repository/"+user);
                    if (!userRep.exists()){
                        userRep.mkdir();
                    }
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }                        
        
        // initialize socket for listening        
        ServerSocket serverSocket = null;
        boolean listening = true;        
        try {
            serverSocket = new ServerSocket(SERVER_LISTENING_PORT);
            System.out.println("Server : Start Listening ...");
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Server : Cannot listen on port "+SERVER_LISTENING_PORT);
            System.exit(-1);
        }        
        
        // start listening
        while(listening){
            new Thread(new ServerHandler( serverSocket.accept())).start();
        }        
        serverSocket.close();
        System.out.println("Server : Close Connection");
        
    }
}
